package com.sptpc.qimoxiangmu.service;

import com.sptpc.qimoxiangmu.controller.request.OrderRequest;
import com.sptpc.qimoxiangmu.model.Model;
import com.sptpc.qimoxiangmu.model.Order;
import com.sptpc.qimoxiangmu.model.vo.OrderDetailVo;
import com.sptpc.qimoxiangmu.repository.ModelRepository;
import com.sptpc.qimoxiangmu.repository.OrderDetailVoRepository;
import com.sptpc.qimoxiangmu.repository.OrderRepository;
import com.sptpc.qimoxiangmu.util.OrderState;
import com.sptpc.qimoxiangmu.util.ServerResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class OrderService {
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private ModelRepository modelRepository;

    @Autowired
    private OrderDetailVoRepository orderDetailVoRepository;

    public ServerResponse save(OrderRequest orderRquest) {
        List<Model> modelList = new ArrayList<>();
        List<Long> longList = orderRquest.getModel();
        for (Long modelId : longList) {
            Optional<Model> optionalModel = modelRepository.findById(modelId);
            if (optionalModel.isPresent()) {
                modelList.add(optionalModel.get());
            }
        }
        Order order=orderRepository.save(Order.builder()
                .customer(orderRquest.getCustomer())
                .items(modelList)
                .state(OrderState.INIT)
                .build());
        return ServerResponse.createBySuccess(order);
    }
    public List<OrderDetailVo> findAllOrder(){
        return orderDetailVoRepository.findAll();
    }

    public List<OrderDetailVo> findOrderBycustomer(String customer) {
        return orderDetailVoRepository.findAllByCustomer(customer);
    }

    public List<OrderDetailVo> finOrderByModelname(String modelname) {
        return orderDetailVoRepository.findAllByModelName(modelname);
    }
    public List<OrderDetailVo> findAllByCustomerAndDrinkName(String customer,String modelName){
        return  orderDetailVoRepository.findAllByCustomerAndModelName(customer,modelName);
    }
    public List<OrderDetailVo> findAllByCreateTimeBetween(LocalDateTime startTime, LocalDateTime endTime){
        return  orderDetailVoRepository.findAllByCreateTimeBetween(startTime,endTime);
    }
}